﻿using System;
using System.Linq;
using System.Windows.Input;

namespace UIConfigTool.ViewModel
{
    public class RelayCommand<T> : ICommand 
    {
        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;

        public RelayCommand(Action<T> execute, Func<T, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        //public bool CanExecute(object parameter)
        //{
        //    return _canExecute?.Invoke((T)parameter) ?? true;
        //}
        public bool CanExecute(object parameter)
        {
            if (parameter is T typedParameter)
            {
                return _canExecute?.Invoke(typedParameter) ?? true;
            }
            else
            {
                // 参数不是预期的类型，根据业务逻辑决定如何处理
                // 可能是记录日志、抛出异常或返回默认值
                return false; // 或者采取其他适当的操作
            }
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }

}
